package cn.wx;

import cn.wx.common.WxServiceRegister;
import cn.wx.common.WxServiceRegisterPostProcessor;
import cn.wx.properties.WxPayProperties;
import com.github.binarywang.wxpay.config.WxPayConfig;
import com.github.binarywang.wxpay.service.WxPayService;
import com.github.binarywang.wxpay.service.impl.WxPayServiceImpl;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.CollectionUtils;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import static cn.wx.properties.WxPayProperties.PREFIX;


/**
 * 微信公众平台注册,使用配置文件的方式
 *
 * @author: sunshaoping
 * @date: Create by in 5:11 下午 2020/5/25
 */
@AllArgsConstructor
public class WxPayServiceRegisterPostProcessor implements WxServiceRegisterPostProcessor {

    private final WxPayProperties properties;

    @Override
    public void processor(WxServiceRegister wxServiceRegister) {
        properties.verification(PREFIX);
        //默认服务
        final WxPayService wxPayService = createWxPayService(properties);
        //注册默认bean
        wxServiceRegister.register(properties.getName(), wxPayService);

        List<WxPayProperties> multiple = properties.getMultiple();
        if (CollectionUtils.isEmpty(multiple)) {
            return;
        }
        Set<String> set = new HashSet<>(multiple.size() + 1);
        set.add(properties.getName());
        for (int i = 0; i < multiple.size(); i++) {
            WxPayProperties wxPayProperties = multiple.get(i);
            String prefix = PREFIX + ".multiple[" + i + "]";
            //验证
            wxPayProperties.verification(prefix);
            String name = wxPayProperties.getName();
            if (set.contains(name)) {
                throw new IllegalStateException(prefix + ".name=" + name + ",已存在");
            }
            set.add(name);
            final WxPayService service = createWxPayService(wxPayProperties);
            //注册bean
            wxServiceRegister.register(name, service);
        }
    }

    protected WxPayService createWxPayService(WxPayProperties properties) {
        final WxPayServiceImpl wxPayService = new WxPayServiceImpl();

        WxPayConfig payConfig = new WxPayConfig();
        payConfig.setAppId(StringUtils.trimToNull(properties.getAppId()));
        payConfig.setMchId(StringUtils.trimToNull(properties.getMchId()));
        payConfig.setMchKey(StringUtils.trimToNull(properties.getMchKey()));
        payConfig.setSubAppId(StringUtils.trimToNull(properties.getSubAppId()));
        payConfig.setSubMchId(StringUtils.trimToNull(properties.getSubMchId()));
        payConfig.setKeyPath(StringUtils.trimToNull(properties.getKeyPath()));

        wxPayService.setConfig(payConfig);

        return wxPayService;
    }
}
